import CreateModal from '@/pages/TableList/components/CreateModal';
import UpdateModal from '@/pages/TableList/components/UpdateModal';
import {
  addBookUsingPost,
  deleteBookUsingPost, listBookByPageUsingPost,
  updateBookUsingPost,
} from '@/services/backend/bookController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import {Button, message, Popconfirm, Typography} from 'antd';
import React, { useRef, useState } from 'react';

const TableList: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.Book>();
  const actionRef = useRef<ActionType>();

  /**
   * 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.Book) => {
    const hide = message.loading('正在添加');
    try {
      await addBookUsingPost({
        ...fields,
      });
      hide();
      message.success('添加成功');
      setCreateModalVisible(false);
      return true;
    } catch (error:any) {
      hide();
      message.error('添加失败'+error.message);
      return false;
    }
  };

  /**
   * 更新节点
   * @param fields
   */
  const handleUpdate = async (fields: API.Book) => {
    if (!currentRow) {
      return;
    }
    const hide = message.loading('正在更新');
    try {
      await updateBookUsingPost({
        id: currentRow.id ?? 0 as any,
        ...fields,
      });
      hide();
      message.success('更新成功');
      return true;
    } catch (error:any) {
      hide();
      message.error('更新失败!'+error.message);
      return false;
    }
  };

  /**
   * 删除节点
   * @param record
   */
  const handleRemove = async (record: API.DeleteRequest) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      await deleteBookUsingPost({
        id: record.id,
      });
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error:any) {
      hide();
      message.error('删除失败'+error.message);
      return false;
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.Book>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: '书名',
      dataIndex: 'bookName',
      valueType: 'text',
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'text',
    },
    {
      title: '价格',
      dataIndex: 'price',
      valueType: 'text',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
        <Popconfirm
          key="config"
          title="您确定要删除么？"
          onConfirm={() => handleRemove(record)}
          okText="确认"
          cancelText="取消"
        >
          <Typography.Link type="danger">删除</Typography.Link>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.Book>
        headerTitle={'CRUD'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const { data, code } = await listBookByPageUsingPost({
            ...params,
            // @ts-ignore
            sorter,
            filter,
          });
          return {
            data: data?.records || [],
            success: code === 0,
            total: data?.total,
          } as any;
        }}
        columns={columns}
      />

      <CreateModal
        columns={columns}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
        onSubmit={async (values) => {
          const success = await handleAdd(values);
          if (success) {
            setCreateModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        visible={createModalVisible}
      />

      <UpdateModal
        columns={columns}
        oldData={currentRow || {}}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
        onSubmit={async (values) => {
          const success = await handleUpdate(values);
          if (success) {
            setUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        visible={updateModalVisible}
      />
    </PageContainer>
  );
};
export default TableList;
